package lixp.security.config;

import lixp.pojo.UpmsUser;
import lixp.security.service.MyDetailService;
import lixp.security.service.SecurityService;
import lixp.utils.Md5util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Collection;

/**
 * 实现自己的AuthenticationProvider类，用来自定义用户校验机制(登录使用)
 */
@Component
public class AuthProvider implements AuthenticationProvider {

    Logger logger = LoggerFactory.getLogger(AuthProvider.class);

    @Autowired
    SecurityService securityService;

    @Autowired
    MyDetailService myDetailService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String usermame = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();

        logger.info(usermame+"----------"+password);

        UpmsUser upmsUser = securityService.getUpmUserByUserName(usermame);
        //判断用户是否存在
        if (null == upmsUser) {
            throw new BadCredentialsException("用户名不存在");
        }
        //判断密码是否正确，这里用了md5+盐的方式
        if (!upmsUser.getPassword().equals(Md5util.md5String(password + upmsUser.getSalt()).toUpperCase())) {
            logger.info("-------------err---------------");
            throw new BadCredentialsException("密码不正确");

        }
        //判断用户是否锁定
        if (upmsUser.getLocked() == 1) {
            throw new BadCredentialsException("账户锁定");
        }

        //用户认证通过就将用户权限装入上下文
        UserDetails userInfo = myDetailService.loadUserByUsername(usermame);
        Collection<? extends GrantedAuthority> authorities = userInfo.getAuthorities();

        return new UsernamePasswordAuthenticationToken(usermame, password,authorities);
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
